<template>
  <el-card>
    <div slot="header">
      <h3>批量新增-SKU信息</h3>
    </div>
    <div>
      <el-row type="flex" justify="end">
        <el-button
          v-if="showBtn('关联商品')"
          type="text"
          size="large"
          @click="handleAssociatedGoods"
          >关联商品</el-button
        >
        <el-button
          v-if="baseTableData.length > 0"
          type="text"
          size="large"
          @click="handleExportData"
          :loading="exportLoading"
          >模板导出</el-button
        >
        <a
          ><Upload
            :show-upload-list="false"
            :format="['xlsx', 'xls', 'csv']"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-format-error="handleUploadFormatError"
            :before-upload="handleBeforeUpload"
            :action="`${uploadBaseURL}sysback/batch/prepare/package/savePackageToPage`"
            ><el-button type="text" size="large">模板导入</el-button
            ></Upload
          ></a
        >
        <el-button
          v-if="baseTableData.length > 0"
          type="text"
          size="large"
          @click="handleSaveData"
          :loading="submitLoading"
        >保存</el-button>
        <el-button
          v-if="baseTableData.length > 0"
          type="text"
          size="large"
          @click="handleSubmitData"
          :loading="submitLoading"
          >提交</el-button
        >
      </el-row>
      <el-row class="format_table_wrap">
        <general-table
          :loading="spuTableLoading"
          :data-source="baseTableData"
          :columns="skuTableColumns"
          @handleCancelSelect="handleCancelSelect"
          @handleChangeInputNumber="handleChangeInputNumber"
        />
      </el-row>
    </div>
    <!-- 关联商品-SPU维度弹框 -->
    <spu-associated-dialog
      ref="spuModal"
      :columns="skuInfoAssociatedColumns"
      :requestApi="requestApi"
      :requestParams="requestParams"
      :distinctParams="distinctParams"
      @getRowList="getAssociatedGoodsAction"
    />
    <!-- 选择计量单位弹框 -->
    <SelectUnitDialog
      :visible.sync="mainUnitVisible"
      @getUnitName="handleReturnMainUnitName"
    />
    <!-- 选择产地弹框 -->
    <original-place-dialog
      :visible.sync="originalPlaceVisible"
      @getOriginalPlace="getOriginalPlaceFn"
    />
  </el-card>
</template>
<script>
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
/* components */
import SpuAssociatedDialog from '@/components/common/dialog/associatedGoods/spuAssociatedDialog';
import GeneralTable from '@/pages/commodity/modules/components/generalTable';
import SelectUnitDialog from '@/pages/commodity/components/SelectUnitDialog';
import OriginalPlaceDialog from '@/components/common/dialog/originalPlaceDialog';
/* mixins */
import spuDimensionMixins from '@/components/common/dialog/associatedGoods/mixins/spuDimension';
/* constants */
import { requiredParams } from '@/components/common/dialog/associatedGoods/constants/spuDimension';
import { batchAddSkuInfoColumnsFn } from '@/pages/commodity/modules/constants/skuInfoModule';
import { ADD_SKU_INFO_AMOUNT } from '@/constants/exportAmountLimit';
/* utils */
import { requestToData, requestToStatus } from '@/api/commonHttp';
import { getSkuVolumnByCalculate } from '@/utils/getUtils';
export default {
  mixins: [spuDimensionMixins],
  components: {
    SpuAssociatedDialog,
    GeneralTable,
    SelectUnitDialog,
    OriginalPlaceDialog
  },
  data () {
    return {
      originalPlaceVisible: false,
      exportLoading: false, // 导出按钮loading
      submitLoading: false, // 提交按钮loading
      requestApi: {
        url: ['/sysback/batch/prepare/package/getProductList'], // 关联商品查询接口
        type: 'post'
      },
      requestParams: requiredParams.requestParams, // 关联商品查询接口所需入参
      distinctParams: requiredParams.distinctParams, // 关联商品查询接口区别未关联和已关联的入参
      skuInfoAssociatedColumns: [
        // 关联商品弹框表格columns
        { type: 'selection', width: 60, align: 'center' },
        { title: '商品名称', key: 'productName', width: 150 },
        { title: 'SPU编码', key: 'spuNo', width: 180 },
        { title: '商品分类', key: 'categoryPath', width: 180 },
        { title: '管理区域', key: 'manageAreaName', width: 150 },
        { title: '规格参数', key: 'saleAttrInfo', width: 150 },
        { title: '品牌', key: 'brandName', width: 150 },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 100
        }
      ],
      skuTableColumns: [], // 表格columns
      spuTableLoading: false, // 表格数据加载loading
      mainUnitVisible: false, // 选择主计量单位弹框开关状态
      storageCurrentRowData: {}, // 存储当前操作row，用于主计量单位的赋值
      linshiBaseTableData: [], // 列表的数据源
      baseTableData: [], // 列表的数据源
      apiObj: {
        baseQueryList: {
          url: '/sysback/batch/add/basicinfo/baseQueryList', // 获取列表数据接口地址
          type: 'post'
        },
        commitBasicInfo: {
          url: '/sysback/batch/prepare/package/commitPackage', // 提交接口地址
          type: 'post' // 接口请求类型
        },
        exportPageToExcelPost: {
          // 模板导出接口地址
          url: '/sysback/batch/prepare/package/exportPageToExcelPost',
          type: 'post'
        }
      },
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  mounted () {
    this.skuTableColumns = _.cloneDeep(
      batchAddSkuInfoColumnsFn({
        handleChooseMainUnit: this.handleChooseMainUnit,
        handleChooseOriginalPlace: this.handleChooseOriginalPlace
      })
    );
    // 刷新页面清除选择的供应商缓存
    window.localStorage.removeItem('selectSupplyList');
  },
  methods: {
    /* 获取产地信息方法 */
    getOriginalPlaceFn (data) {
      let { producingAreaName, producingAreaCode } = data;
      let { index } = this.storageCurrentRowData;
      this.baseTableData[index].producingAreaName = producingAreaName;
      this.baseTableData[index].producingAreaCode = producingAreaCode;
    },
    /* 选择产地事件 */
    handleChooseOriginalPlace ({ index }) {
      this.storageCurrentRowData.index = index;
      this.originalPlaceVisible = true;
    },
    /* 初始化表格数据 */
    initTableDataFn (isImport) {
      this.baseTableData = this.linshiBaseTableData.reduce((value, item) => {
        item.packageList.forEach((row) => {
          value.push({
            ...item.main,
            ...row
          });
        });
        return value;
      }, []);
      /* 如果是导入数据，需要自动计算row的体积 */
      if (!isImport) {
        return false;
      }
      this.baseTableData.forEach((row) => {
        row.singleVolume = getSkuVolumnByCalculate({ type: { start: 'single' }, row });
        row.oneVolume = getSkuVolumnByCalculate({ type: { start: 'one' }, row });
        row.twoVolume = getSkuVolumnByCalculate({ type: { start: 'two' }, row });
        row.threeVolume = getSkuVolumnByCalculate({ type: { start: 'three' }, row });
      });
    },
    /* 计算体积 */
    handleChangeInputNumber (data) {
      let { row, columnName } = data;
      let typeSplit = _.lowerCase(columnName).split(' '); // 转换字符串string以空格分开单词，并转换为小写,并通过split切割成对应的数组
      let type = typeSplit[0]; // 只取第一项，分别对应 single one two three四种情况
      row[`${type}Volume`] = getSkuVolumnByCalculate({ type: { start: type }, row });
    },
    /* 获取选择的主计量单位值 */
    handleReturnMainUnitName (unitName) {
      let { type, index } = this.storageCurrentRowData;
      this.baseTableData[index][type] = unitName;
    },
    /* 选择主计量单位 */
    handleChooseMainUnit (data) {
      this.storageCurrentRowData = data;
      this.mainUnitVisible = true;
    },
    /* 关联商品 */
    handleAssociatedGoods () {
      let curBtnId = getBtnsId('关联商品');
      sessionStorage.setItem('buttonId', curBtnId);
      this.CHANGE_MODAL_SWITCH(true);
      /* this.$nextTick(() => {
        this.$refs.spuModal.getDataListAction();
      }); */
    },
    /* 关联商品获取表格数据 */
    getAssociatedGoodsAction () {
      let dataList = this.getListFromMapFn().map((value) => {
        return value.uuid;
      });
      // let data = { productUuidList: dataList.join(',') }
      let data = dataList;
      if (dataList.length !== 0) {
        this.spuTableLoading = true;
        ApiRequest(
          `/sysback/batch/prepare/package/queryPackageList`,
          'post',
          data,
          false
        )
          .then((res) => {
            this.spuTableLoading = false;
            if (res.retStatus !== '1') {
              return;
            }
            this.linshiBaseTableData = res.retData;
            this.initTableDataFn();
          })
          .catch((err) => {
            console.log(err);
            this.spuTableLoading = false;
          });
      } else {
        this.linshiBaseTableData = [];
        this.baseTableData = [];
      }
    },
    /* 取消对应表格row */
    handleCancelSelect (data) {
      let { row } = data;
      this.handleDeleteSpuRow(row, this.baseTableData, 'productUuid');
      this.$nextTick(() => {
        this.getAssociatedGoodsAction();
      });
    },
    // 获取提交保存入参
    getParamsBySaveOrSubmit () {
      // 数据重组,根据productUuid将list转成数组.
      return this.baseTableData.reduce((value, item) => {
        const index = _.findIndex(value, (elem) => {
          return elem.productUuid === item.productUuid;
        });
        if (index === -1) {
          value.push({
            productUuid: item.productUuid,
            packageList: [item]
          });
        } else {
          value[index].packageList.push(item);
        }
        return value;
      }, []);
    },
    // 保存
    async handleSaveData () {
      const retStatus = await requestToStatus({
        url: '/sysback/batch/prepare/package/savePackage',
        type: 'post',
        data: { inputList: this.getParamsBySaveOrSubmit() }
      }, () => { this.submitLoading = true; }, () => { this.submitLoading = false; });
      if (retStatus) {
        this.$message.success('提交成功');
        this.baseTableData = [];
        this.$router.push({ name: 'commodityNotPerfection' }); // 跳转待准入页面
      }
    },
    /* 提交数据 */
    async handleSubmitData () {
      if (this.baseTableData.length > ADD_SKU_INFO_AMOUNT) {
        return this.$message.warning(`当前单据提交的行数不能超过${ADD_SKU_INFO_AMOUNT}`)
      }
      const retData = await requestToData({
        url: '/sysback/batch/prepare/package/commitPackage',
        type: 'post',
        data: { inputList: this.getParamsBySaveOrSubmit() }
      }, () => { this.submitLoading = true; }, () => { this.submitLoading = false; });
      if (!retData) { return false; }
      const { isSuccess, inputList } = retData;
      if (isSuccess) {
        this.$message.success('提交成功');
        this.baseTableData = [];
        this.$router.push({ name: 'commodityNotPerfection' }); // 跳转待准入页面
      } else {
        this.$message.warning('存在异常信息，请完善后再提交');
        this.skuTableColumns = [
          {
            title: '异常原因',
            key: 'errorMsg',
            sortable: true,
            errorTip: true,
            notShowTip: true
          },
          ...this.skuTableColumns.filter(item => item.key !== 'errorMsg')
        ]
        this.baseTableData = _.flatten(inputList.map(item => item.packageList));
      }
    },
    /* 导出数据 */
    handleExportData () {
      let data = this.baseTableData.reduce((value, item) => {
        let index = _.findIndex(value, (elem) => {
          return elem.productUuid === item.productUuid;
        });
        if (index === -1) {
          value.push({
            productUuid: item.productUuid,
            packageList: [item]
          });
        } else {
          value[index].packageList.push(item);
        }
        return value;
      }, []);
      this.exportLoading = true;
      ApiRequestExportTable(
        this.apiObj.exportPageToExcelPost.url,
        this.apiObj.exportPageToExcelPost.type,
        data,
        false
      )
        .then((res) => {
          this.exportLoading = false;
          const blob = new Blob([res], {
            type: 'application/octet-stream'
          });
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = '批量维护SKU信息.xlsx';
          link.click();
          window.URL.revokeObjectURL(blob); // 释放掉blob对象
        })
        .catch((err) => {
          this.exportLoading = false;
          console.log(err);
          this.$Message.error('导出失败');
        });
    },
    /* 上传格式验证失败 */
    handleUploadFormatError (file, fileList) {
      this.spuTableLoading = false;
      this.$Message.error('格式错误');
    },
    /* 上传之前 */
    handleBeforeUpload () {
      this.spuTableLoading = true;
      this.linshiBaseTableData = [];
      this.baseTableData = [];
    },
    /* 上传成功 */
    handleUploadSuccess (file) {
      this.spuTableLoading = false;
      if (file.retStatus === '1') {
        // 如果上传成功,并且接口返回成功,对表格进行赋值操作.
        this.linshiBaseTableData = file.retData;
        this.initTableDataFn(true);
      } else {
        // 如果接口返回失败,就打印失败信息
        this.$Message.error(file.retMessage);
      }
    },
    /* 上传失败 */
    handleUploadError () {
      this.spuTableLoading = false;
      this.$Message.error('上传失败');
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .ivu-upload {
  margin: 0 5px;
}
</style>
